package com.mall.order.mq.delayorder;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @author : xfeng
 * @time : 2021/8/30 15:54
 * @program: myproject3
 * @description:
 */
@Component
@Slf4j
public class DelayOrderCancelProducer {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init(){
        producer = new DefaultMQProducer("delay_order_cancel_producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
            log.error(e.getErrorMessage());
        }
    }

    /**
     * 发送消息
     * @param orderId
     * @return
     */
    public boolean sendDelayOrderCancelMessage(String orderId){
        Message message = new Message("delay_order_cancel", orderId.getBytes(Charset.forName("utf-8")));

        //  1s   5s  10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        //  1    2    3  4   5  6  7  8  9 10  11 12 13 14 15  16   17 18

        message.setDelayTimeLevel(4);
        SendResult send = null;
        try {
            send = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(send != null && send.getSendStatus().equals(SendStatus.SEND_OK)){
            return true;
        }

        return false;

    }

}
